//1.引入multer中间件
const multer = require("multer");
const path = require("path")
const { port } = require("../bin/www")
//2.把这些代码 放入一个函数
const uploads = (req, res, next) => {
    const storage = multer.diskStorage({
        destination(req, file, cb) {
            console.log(file)
            cb(null, path.resolve('./uploads'))//上传文件存储的路径
        },
        filename(req, file, cb) {
            //保存的文件没有后缀名 所以需要添加后缀名
            //timg.jpg
            let fileName = /\.[^\.]+$/.exec(file.originalname)
            fileName = file.fieldname + '-' + Date.now() + fileName[0]
            //把地址添加到req.body
            req.body.companyLogo = "http://127.0.0.1:" + "/" + fileName
            cb(null, fileName)//设置上传文件的名字
        }
    })

    var upload = multer({ storage: storage }).single('companyLogo')

    upload(req, res, function (err) {
        if (err instanceof multer.MulterError) {
            console.log(err)
            res.send("上传文件出错")
        } else {
            next()
        }
    })
}
module.exports = {
    uploads
}